package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            //当前拦截到的不是controller方法直接放行
            return true;
        }

        String jwtToken = request.getHeader(jwtProperties.getAdminTokenName());
        log.info("当前请求token:"+jwtToken);
        Claims body = null;
        try {
            body = Jwts.parser()
                    .setSigningKey(jwtProperties.getAdminSecretKey())
                    .parseClaimsJws(jwtToken)
                    .getBody();
            String empIdStr= body.get(JwtClaimsConstant.EMP_ID).toString();
            long empId= Long.valueOf(empIdStr);
            BaseContext.setEmpId(empId);
            log.info("当前请求empId:"+empId);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(401);
            return false;
        }

        return true;
    }
}
